import { defineStore } from "pinia"
import { ref, computed } from 'vue'
import { login, register, getUserInfo } from '@/api/auth'
import { setToken, getToken, removeToken } from '@/utils/storage'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(getToken() || '')
  const userInfo = ref({})
  const isAuthenticated = computed(() => !!token.value)

  // 登录
  const handleLogin = async (loginData) => {
    try {
      const response = await login(loginData)

      // 存储token
      token.value = response.access
      setToken(response.access, response.refresh)

      // 设置用户信息（不包含密码）
      userInfo.value = {
        username: loginData.username,
        email: response.email || ''
      }

      return response
    } catch (error) {
      console.error('登录失败:', error)
      throw error
    }
  }
  // 注册
  const handleRegister = async (registerData) => {
    try {
      const response = await register(registerData)
      return response
    } catch (error) {
      console.error('注册失败:', error)
      throw error
    }
  }

  // 获取用户信息
  const getCurrentUserInfo = async () => {
    try {
      // 如果后端提供了用户信息接口
      if (getUserInfo) {
        const response = await getUserInfo()
        userInfo.value = response
        return response
      }

      console.log('后端没有提供用户信息接口')
      return null
    } catch (error) {
      console.error('获取用户信息失败:', error)
      throw error
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    removeToken()
  }

  return {
    token,
    userInfo,
    isAuthenticated,
    handleLogin,
    handleRegister,
    getCurrentUserInfo,
    logout
  }
})
